package com.ndood.admin.core.security.xss;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang.StringEscapeUtils;

/**
 * https://www.cnblogs.com/woaiadu/p/7216332.html
 * 防止xss攻击
 */
public class XSSRequestWrapper extends HttpServletRequestWrapper {

	/**
	 * 构造方法
	 */
	public XSSRequestWrapper(HttpServletRequest request) {
		super(request);
	}

	/**
	 * 处理参数值
	 */
	@Override
	public String[] getParameterValues(String parameter) {
		String[] values = super.getParameterValues(parameter);
		if (values == null) {
			return null;
		}
		int count = values.length;
		String[] encodedValues = new String[count];
		for (int i = 0; i < count; i++) {
			encodedValues[i] = dealString(values[i]);
		}
		return encodedValues;
	}

	/**
	 * 覆盖
	 */
	@Override
	public String getParameter(String parameter) {
		String value = super.getParameter(parameter);
		return dealString(value);
	}

	@Override
	public String getHeader(String name) {
		String value = super.getHeader(name);
		return dealString(value);
	}

	/**
	 * 字符串处理
	 */
	private String dealString(String value) {
		if (value != null) {
			// 采用spring的StringEscapeUtils工具类 实现
			StringEscapeUtils.escapeHtml(value);
			StringEscapeUtils.escapeJavaScript(value);
			StringEscapeUtils.escapeSql(value);
		}
		return value;
	}

}